package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.LoginSessionUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ALiSendMessage;
import com.itheima.reggie.utils.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Value("${aliyun.sms.codeLength}")
    private int codeLength;
    @Autowired
    private UserService userService;

    @Autowired
    private ALiSendMessage aLiSendMessage;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/login")
    public R<User> loginUser(@RequestBody User user, String code, HttpSession session) {
        System.out.println("用户输入的验证码为:"+code);
        //String checkCode=(String) session.getAttribute("code");
        //取出redis中的验证码
        String checkCode =(String) redisTemplate.opsForValue().get(user.getPhone());
        if (!code.equals(checkCode)){
            return R.error("验证码错误!");
        }
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User user2=userService.getOne(queryWrapper);
        if (user2 != null) {
            //登陆成功 存入session
            session.setAttribute("userLogin", user2);
            //判断是否已经登录
            if (LoginSessionUtil.sessionMap.containsKey(user2.getId())) {
//                LoginSessionUtil.sessionMap.get(login.getId()).removeAttribute("loginUser");
                //如果已登录则删除该session的对象
                LoginSessionUtil.sessionMap.get(user2.getId()).setAttribute("userLogin", "异地登录");
            }
            LoginSessionUtil.sessionMap.put(user2.getId(), session);
            //用户登录成功 删除验证码缓存
            redisTemplate.delete(user.getPhone());
           return R.success(user);
        }else {
            //初始化姓名
            user.setName(user.getPhone()+"_p");
            //初始化用户状态
            user.setStatus(1);
            //用户未注册 自动注册
            userService.save(user);
            session.setAttribute("userLogin", user);
            LoginSessionUtil.sessionMap.put(user.getId(), session);
            return  R.success(user);
        }
    }

    @PostMapping("/logout")
    public R<String> loginUser(HttpSession session) {
        User login=(User) session.getAttribute("userLogin");
        LoginSessionUtil.sessionMap.remove(login.getId());
        session.removeAttribute("userLogin");
        return R.success("");
    }

    @GetMapping("sendMes")
    public R<String> sendMsg(String phone ,HttpSession session) throws Exception {
        String code=SendMessage.createCode(codeLength);
        aLiSendMessage.sendMsg(phone,code);
        log.info(phone+"验证码========"+code);
        //session.setAttribute("code", code);
        //将验证码存到redis中
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("验证码获取成功!");
    }

}
